package com.whfc.iot.mach.processor;

import com.whfc.common.constant.QueueConst;
import com.whfc.common.spring.AppContextUtil;
import com.whfc.common.util.JSONUtil;
import com.whfc.iot.mach.constant.MsgConst;
import com.whfc.iot.mach.entity.MachMsg0x05;
import com.whfc.iot.mach.entity.MachMsg0x85;
import com.whfc.iot.mach.event.DeviceOnlineEvent;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description: 0x05消息处理
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/17 9:17
 */
@Component
public class MachUpMsgProcessor0x05 implements MachUpMsgProcessor<MachMsg0x05> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private SessionManager sessionManager;

    @Override
    public void processMsg(MachMsg0x05 reqMsg) {

        Integer deviceId = reqMsg.getDeviceId();
        logger.info("处理0x05数据:{}", JSONUtil.toString(reqMsg));

        //构造0x85
        MachMsg0x85 resMsg = new MachMsg0x85();
        resMsg.setStartFlag(reqMsg.getStartFlag());
        resMsg.setDeviceType(reqMsg.getDeviceType());
        resMsg.setSeq(reqMsg.getSeq());
        resMsg.setDeviceId(reqMsg.getDeviceId());
        resMsg.setCmd(MsgConst.DOWNSTREAM_CMD_0x85);
        resMsg.setResult(reqMsg.isCheckSuccess() ? MsgConst.ACK_SUCCESS : MsgConst.ACK_FAIL);

        //响应0x85
        Session session = sessionManager.getSessionByDeviceId(deviceId);
        session.getChannel().writeAndFlush(resMsg).addListener(future -> {
            logger.info("0x85发送结果,deviceId={},isDone={},isSuccess={}", deviceId, future.isDone(), future.isSuccess());
        });

        String textMsg = JSONUtil.toString(reqMsg);
        //入消息队列
        try {
            amqpTemplate.convertAndSend(QueueConst.OBD_DATA, textMsg);
        } catch (Exception ex) {
            logger.error("", ex);
        }

        //发布升级事件
        DeviceOnlineEvent event = new DeviceOnlineEvent(reqMsg.getDeviceType(), reqMsg.getDeviceId(), reqMsg.getSeq(), reqMsg.getMasterVer());
        AppContextUtil.context().publishEvent(event);
    }
}
